/**
 * Copyright (c) 2015-2016, Michael Yang 杨福海 (fuhai999@gmail.com).
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.model.query;

import com.jfinal.plugin.activerecord.Page;
import io.jpress.model.HouseData;
import io.jpress.model.Metadata;
import io.jpress.model.TjDzcy;
import io.jpress.model.TjKjcg;

import java.math.BigInteger;
import java.util.List;

public class TjDzcyQuery extends JBaseQuery {
	protected static final TjDzcy DAO = new TjDzcy();
	private static final TjDzcyQuery QUERY = new TjDzcyQuery();

	public static TjDzcyQuery me() {
		return QUERY;
	}

	public List<TjDzcy> findList() {
		StringBuilder sqlBuilder = new StringBuilder("select * from jpress_tj_dzcy u order by month Asc");

		return DAO.find(sqlBuilder.toString());

	}

	public TjDzcy findFirstFromMetadata(String key, Object value) {
//		return DAO.findFirstFromMetadata(key, value);
		Metadata md = MetaDataQuery.me().findFirstByTypeAndValue(TjDzcy.METADATA_TYPE, key, value);
		if (md != null) {
			BigInteger id = md.getObjectId();
			return findById(id);
		}
		return null;
	}

	public Page<TjDzcy> paginate(int pageNumber, int pageSize , String orderby) {
		String select = "select * ";
		StringBuilder fromBuilder = new StringBuilder(" from jpress_tj_dzcy u ");
		buildOrderBy(orderby, fromBuilder);
		return DAO.paginate(pageNumber, pageSize, select, fromBuilder.toString());
	}

	public long findCount() {
		return DAO.doFindCount();
	}

	public TjDzcy findById(final BigInteger houseDataId) {
		return DAO.findById(houseDataId);
	}

	protected static void buildOrderBy(String orderBy, StringBuilder fromBuilder) {
		if ("month".equals(orderBy)) {
			fromBuilder.append(" ORDER BY u.month DESC");
		}
	}

	public void deleteById(BigInteger id) {
		DAO.deleteById(id);
	}

}
